package com.chiaching.webmagic.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.net.URLEncoder;
import com.chiaching.webmagic.domain.bo.JdGoodSearchBO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.Charsets;
import org.bouncycastle.util.encoders.UTF8;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Component;
import sun.nio.cs.UTF_32;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @email 1738870995@qq.com
 * @author: 何佳靖
 * @date: 2022/3/26 11:10
 */
@Component
@Slf4j
public class JdSearchUtils {


    public static void main(String[] args) {
        System.out.println(new JdSearchUtils().search("java").toString());
    }



    public List<JdGoodSearchBO> search(String goodName){
        ArrayList<JdGoodSearchBO> resp = new ArrayList();
        try {
            goodName = Validator.isChinese(goodName) ? URLEncoder.createAll().encode(goodName, Charsets.UTF_8) : goodName;
            Document document = Jsoup.connect(String.format("https://search.jd.com/Search?keyword=%s", goodName)).get();
            Element goodsList = document.getElementById("J_goodsList");
            if (Objects.nonNull(goodsList) && CollUtil.isNotEmpty(goodsList.getElementsByTag("li"))){
                for (Element li : goodsList.getElementsByTag("li")) {
                    JdGoodSearchBO jdGoodSearchBO = new JdGoodSearchBO();
                    jdGoodSearchBO.setImg("https:"+li.getElementsByTag("img").eq(0).attr("data-lazy-img"));
                    jdGoodSearchBO.setPrice(li.getElementsByClass("p-price").select("i").eq(0).text());
                    jdGoodSearchBO.setDesc(li.getElementsByClass("p-name").eq(0).select("i").eq(0).text());
                    jdGoodSearchBO.setTitle(li.getElementsByClass("p-name").eq(0).select("em").eq(0).text());
                    resp.add(jdGoodSearchBO);
                }
            }
            return resp;
        } catch (Exception e) {
            log.error("爬取京东商品出现异常!",e);
        }
        return Collections.emptyList();
    }
}
